package com.hctforgreen.greenservice.db;
 
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Environment;
import android.util.Log;

import com.hctforgreen.greenservice.R;
/**
 * 处理本地省市区数据库
 * @author ld
 * 20140402
 *
 */
public class DBCityManager {
    private final int BUFFER_SIZE = 1024;
  /*
   * 若更新省市数据库文件，可以更新数据库文件后，改变DB_NAME值，手机app即可更新
   * wuhs20151125
   */
//    public static final String DB_NAME = "locationdb_v4.s5db";
    public static final String DB_NAME = "locationdb_v5.s3db";
    public static final String PACKAGE_NAME = "com.hctforgreen.greenservice";
    public static final String DB_PATH = "/data"
            + Environment.getDataDirectory().getAbsolutePath() + "/"+ PACKAGE_NAME;
    private SQLiteDatabase database;
    private Context context;
    private File file=null;
    
    public DBCityManager(Context context) {
        this.context = context;
    }
 
    public void openDatabase() {
        //用于打开和更新数据库
        this.database = this.openDatabase(DB_PATH + "/" + DB_NAME);
    }
    public SQLiteDatabase getDatabase(){
    	return this.database;
    }
 
    private SQLiteDatabase openDatabase(String dbfile) {
        try {
        	file = new File(dbfile);
            if (!file.exists()) {
            	/**
            	 * 若更新省市数据库文件，可以更新数据库文件后，改变DB_NAME值,同时更改引用数据库文件的值
            	 * 2016-5-10
            	 * 390694--更改引用文件名
            	 */
            	InputStream is = context.getResources().openRawResource(R.raw.locationdb_v5);//引用数据库文件
            	if(is!=null){
//            		Log.e("cc", "is null");
            	}else{
            	}
            	FileOutputStream fos = new FileOutputStream(dbfile);
            	if(is!=null){
//            		Log.e("cc", "fosnull");
            	}else{
            	}
                byte[] buffer = new byte[BUFFER_SIZE];
                int count = 0;
                while ((count =is.read(buffer)) > 0) {
                    fos.write(buffer, 0, count);
//                		Log.e("cc", "while");
                	fos.flush();
                }
                fos.close();
                is.close();
            }
            database = SQLiteDatabase.openOrCreateDatabase(dbfile,null);
            return database;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e){
        }
        return null;
    }
    public void closeDatabase() {
    	if(this.database!=null)
    		this.database.close();
    }
}